<template>
  <div class="Diary">
    <Nav></Nav>
    <Leader gameName="五子棋" ref="lea"></Leader>
    <div class="diary-main">

      <el-timeline>
        <el-card style="width:450px;">
          <pre style="text-align: center">对手：{{ opponentName }}</pre>
        </el-card>
      </el-timeline>
      <el-timeline>
        <el-card style="width:450px; margin-bottom: 20px">
          <pre style="text-align: center">{{ info }}</pre>
        </el-card>
      </el-timeline>
      <div v-if="over">
        <el-button type="success" style="text-align: center ;width: 450px" round
                   @click="this.goHall">
          返回大厅
        </el-button>
      </div>


      <div class="container">
        <div>
          <canvas
              id="canvas"
              ref="canvas"
              width="800"
              disabled="true"
              height="600"
              @mousedown="canvasDown($event)"
          ></canvas>
        </div>

      </div>
    </div>
  </div>


</template>
<script defer=true>
import Nav from "../../components/Nav";
import Leader from "../../components/Leader";
import request from "../../api";

import "../../assets/js/phaser.min.js";
// import initGame from "../../assets/js/script.js";
// import  from "@/assets/js/dateformat";
const gamestatestx = require("../../assets/js/catch-the-cat.js");


export default {
  name: "goBang",
  components: {Nav, Leader},
  data() {
    return {
      context: {},
      me: false,
      over: false,
      location: {
        x: "",
        y: "",
        color: ""
      },
      chessBoard: [],
      game: "",
      gamestate: "",
      userId: "",
      record: "未登录",//得分
      setinterval1: 0,
      websock: {},
      chess: {},

      info: "",
      thisInfo: "我方落子",
      thatInfo: "等待对方落子",
      color: "",
      opponentName: ""

    };
  },
  watch: {},
  methods: {
    initDraw() {
      for (let i = 0; i < 15; i++) {
        this.chessBoard[i] = [];
        for (let j = 0; j < 15; j++) {
          this.chessBoard[i][j] = 0;
        }
      }

      const canvas = document.querySelector('#canvas');
      this.context = canvas.getContext('2d');
      this.context.strokeStyle = "#0A0A0A";
      // 背景图片
      let logo = new Image();
      logo.src = require("./chess.jpg");
      var context = this.context;
      logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        // 绘制棋盘网格
        for (let i = 0; i < 15; i++) {
          context.moveTo(15 + i * 30, 15);
          context.lineTo(15 + i * 30, 430);
          context.stroke();
          context.moveTo(15, 15 + i * 30);
          context.lineTo(435, 15 + i * 30);
          context.stroke();
        }
      }

    },
    //棋盘点击事件
    canvasDown(e) {
      if (this.over) {
        return;
      }
      if (!this.me) {
        return;
      }
      let x = e.offsetX;
      let y = e.offsetY;
      // 注意, 横坐标是列, 纵坐标是行

      this.location.x = Math.floor(x / 30);
      this.location.y = Math.floor(y / 30);
      this.location.color = 0;
      console.log(this.chessBoard[this.location.y][this.location.x]);
      if (this.chessBoard[this.location.y][this.location.x] == 0) {
        // TODO 发送坐标给服务器, 服务器要返回结果
        this.websock.send(JSON.stringify(this.location));
        this.oneStep(this.location.x, this.location.y, this.isWhite);
        this.chessBoard[this.location.y][this.location.x] = 1;
      }
    },

    //渲染棋子
    oneStep(i, j, isWhite) {
      this.context.beginPath();
      this.context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
      this.context.closePath();
      var gradient = this.context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
      if (isWhite === -1) {
        gradient.addColorStop(0, "#0A0A0A");
        gradient.addColorStop(1, "#636766");
      } else {
        gradient.addColorStop(0, "#D1D1D1");
        gradient.addColorStop(1, "#F9F9F9");
      }
      this.context.fillStyle = gradient;
      this.context.fill();
    },

    socketInit: function () {
      var user = this.$store.state.user;
      if (JSON.stringify(user) !== "{}" && JSON.stringify(user) !== undefined) {
        //已经登陆了
        this.userId = user.id;
      } else {
        this.$message.error("未登录!请登陆后,匹配开始游戏");
        this.$router.push("/game");
        return;
      }
      const hh = window.location.href
      let url;
      if (hh.indexOf('https') > -1) {
        url = "wss://"+this.$config.websocketurl+"/pvpGame?userId="+this.userId;
      } else {
        url = "ws://"+this.$config.websocketurl+"/pvpGame?userId="+this.userId;
      }
      console.log(url);
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    },
    websockSendMessage(e) {
      //测试
      this.websock.send("helllo?");
    },
    websocketonopen: function () {
      console.log("WebSocket连接成功");
    },
    websocketonerror: function (e) {
      console.log("WebSocket连接发生错误");
    },
    //接受服务端返回数据
    websocketonmessage: function (e) {

      let parse = JSON.parse(e.data);
      console.log(parse);
      if (!parse.ok) {
        this.$message.error(parse.message);
        this.$router.push("/game");
      }
      if (parse.reason === "begin") {
        //开始游戏
        this.color = parse.color;
        console.log("begin:" + parse.message);
        if (parse.message === "-1") {
          //当前玩家是黑子，先落子
          this.me = true;
          this.info = this.thisInfo;

        } else {
          //当前玩家是白子，后落子
          this.me = false;
          this.info = this.thatInfo;
        }
      } else if (parse.reason === "info") {
        //初始化信息
        this.info = parse.message;
        if(this.opponentName===""){
          this.opponentName = parse.opponentName
        }
      } else if (parse.reason === "playing") {
        //判断谁落子，谁等待
        console.log(this.color === parse.color);
        if (this.color === parse.color) {
          //等待对方落子
          this.me = false;
          this.info = this.thatInfo;
        } else {
          //该我方落子了
          this.me = true;
          this.info = this.thisInfo;
        }
        //判断游戏是否结束
        if (parse.over) {
          this.over = true;
          if (parse.winnerUserId === this.userId) {
            this.info = "你赢啦！！！！！";
            //保存战绩
            // this.$ajax.post(this.$config.url + `/game/saveGameScore`, {
            //   personId: this.userId,
            //   gameName: "五子棋",
            //   score: 1,
            // }).then(() => {
            //   this.update();
            // }).catch(() => {
            // });
            // document.getElementById("canvas").onmousedown = false
            this.websocketclose();
          } else {
            this.info = "你输啦！！！！！";
            // this.$ajax.post(this.$config.url + `/game/saveGameScore`, {
            //   personId: this.userId,
            //   gameName: "五子棋",
            //   score: -1,
            // }).then(() => {
            //   this.update();
            // }).catch(() => {
            // });
            // document.getElementById("canvas").onmousedown = false
            this.websocketclose();
          }
        }
        this.chessBoard[parse.y][parse.x] = 1;
        this.oneStep(parse.x, parse.y, parse.color)
      } else {
        return;
      }
    },
    websocketclose: function (e) {
      console.log("connection 关闭");
      this.websock.close();
    },
    update() {
      this.$refs.lea.updateLeader();
    },
    goHall(e) {
      //测试
      this.$router.push("/play/在线五子棋");
    },
  },
  mounted() {
    this.initDraw();
  },
  created() {
    this.socketInit();
  },
  destroyed: function () {
    if (!this.over) {
      this.websock.send
      this.$message.info("您逃跑啦！")
    }
    this.websock.close();
  }

};
</script>

<style scoped lang="less">

.Diary {
  box-sizing: border-box;
  max-width: 1360px;
  width: 100%;
  padding: 80px 50px;
  margin: 0 auto;

  .diary-main {
    box-sizing: border-box;
    width: 100%;
    padding: 30px 8% 30px 20%;
    //background-color: rgba(255, 255, 21, 1);
    border-radius: 15px;

    .el-timeline {
      /deep/ .el-timeline-item__timestamp {
        position: absolute;
        top: -8px;
        left: -134px;
        font-size: 20px;
        font-weight: bolder;
        color: #6bc30d;
      }

      .el-timeline-item {
        .el-card {
          pre {
            font-size: 14px;
            line-height: 30px;
          }
        }
      }
    }
  }
}

#screen {
  font-size: 22px;
  text-align: center;
  background-color: rgba(255, 255, 255, 0);
  color: yellow;
  margin-bottom: 20px;
}
</style>